package ctm.javacode;

import java.io.* ;
import java.sql.*;
import java.util.Properties;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@WebServlet("/sendPW.do") 

public class sendPW extends HttpServlet {
	
	private final String SUCCESS_VIEW = "index.jsp"; 
	private final String ERROR_VIEW = "forgetPwError.jsp"; 
	
	private String mail = "";
	private String pw = "";
	
	private final String MAILHOST = "smtp.gmail.com";
	private final String MAILPORT = "465";
	private final String SERVER = "pllabictm@gmail.com";
	private final String PW = "891216aa";
	private Properties props ;
	
	protected void doPost(HttpServletRequest request,
								HttpServletResponse response )
								throws ServletException, IOException {

		String ac = request.getParameter("ac");
		mail = request.getParameter("email");
		HttpSession requests = request.getSession();

		try {
			if (checkAccount(ac)) {
				props = new Properties();
				props.put("mail.smtp.host", MAILHOST);
				props.setProperty("mail.smtp.socketFactory.class",
						"javax.net.ssl.SSLSocketFactory");
				props.setProperty("mail.smtp.socketFactory.fallback", "false");
				props.setProperty("mail.smtp.port", MAILPORT);
				props.setProperty("mail.smtp.auth", "true");

				Session session = Session.getDefaultInstance(props,
						new Authenticator() {
							protected PasswordAuthentication getPasswordAuthentication() {
								return new PasswordAuthentication(SERVER, PW);
							}
						});

				Message message = new MimeMessage(session);
				message.setFrom(new InternetAddress(SERVER));
				message.setRecipient(Message.RecipientType.TO,
						new InternetAddress(mail));
				message.setSubject("中醫問卷系統密碼信");
				message.setText("您的密碼:" + pw);
				Transport.send(message);

				requests.setAttribute("sendPW", "sendpw");
				// response.sendRedirect(SUCCESS_VIEW);
				request.getRequestDispatcher(SUCCESS_VIEW).forward(request,
						response);
			} // end if
			else {
				response.sendRedirect(ERROR_VIEW);
			}
		} catch (SQLException e) {

			e.printStackTrace();
		} // end else
		catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} // end doPost()
	
	

	
	private boolean checkAccount(String username) throws SQLException, NamingException {
		
		Boolean isUser = false ;
		dbBean db = new dbBean("jdbc/ctmpllab") ;
		ResultSet rs ;
		String newPW = "";

        
		db.Connected();		
		try {
			rs = db.ExcuteQuery("SELECT * FROM accounttable");		    
		} catch(SQLException e) {
			throw new SQLException(e) ;
		} // end try-catch
			
		while ( rs.next() ) {
			if (rs.getString("account").trim().equals(username)
					&& rs.getString("email").trim().equals(mail) ) {
				isUser = true ;
				pw = lib.GeneratePW();
				newPW = md5Encrypt.generate(pw);//用md5加密帳戶密碼
				String sqlQuery = "UPDATE accounttable SET PASSWORD = '" + newPW + "' WHERE ACCOUNT = '" + username + "'";
					
				db.ExcuteUpdate(sqlQuery);	 
				break;
			} // end if
		} // end while
		db.CloseConn() ; // 資料庫關閉
	
		
		return isUser ;
	} // end checkLogin()

	
} // end class login()





